package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.constant.RedisConstants;
import com.hmdp.constant.SystemConstants;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheUtils;
import com.hmdp.utils.RedisData;
import lombok.NonNull;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private CacheUtils cacheUtils;

    /**
     * 根据id查询商铺信息-NULL直接解决缓存穿透问题
     * @param id
     * @return
     */
    @Override
    public Result queryById(Long id) {

//        Shop shop = queryWithRedisCache(id);

//        Shop shop = queryWithPassThrough(id);

//        Shop shop = cacheUtils.queryWithPassThrough(RedisConstants.RedisShopConstants.CACHE_SHOP_KEY_PREFIX,
//                id, Shop.class,
//                this::getById,
//                RedisConstants.RedisShopConstants.CACHE_SHOP_TTL,
//                TimeUnit.MINUTES);

//        Shop shop = queryWithMutex(id);

//        Shop shop = queryWithLogicalExpire(id);
//        Shop shop = cacheUtils.queryWithLogicalExpire(RedisConstants.RedisShopConstants.CACHE_SHOP_KEY_PREFIX,
//                id,
//                Shop.class,
//                RedisConstants.RedisShopConstants.LOCK_SHOP_KEY_PREFIX,
//                this::getById,
//                RedisConstants.RedisShopConstants.CACHE_SHOP_TTL,
//                TimeUnit.MINUTES);

        Shop shop = cacheUtils.queryWithLogicalExpire(RedisConstants.RedisShopConstants.CACHE_SHOP_KEY_PREFIX,
                id,
                Shop.class,
                RedisConstants.RedisShopConstants.LOCK_SHOP_KEY_PREFIX,
                this::getById,
                20L,
                TimeUnit.SECONDS);


        if (shop == null) {
            return Result.fail("店铺不存在！");
        }
        return Result.ok(shop);
    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    /**
     * 根据id查询商铺信息-逻辑过期解决缓存击穿问题(不需要考虑缓存穿透问题，所以不用缓存NULL值了，因为热key来自于缓存预热ApplicationInit)
     * @param id
     * @return
     */
    private Shop queryWithLogicalExpire(Long id){
        //从redis查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(RedisConstants.RedisShopConstants.CACHE_SHOP_KEY_PREFIX + id);

        //不存在直接NULL
        if (StrUtil.isBlank(shopJson)) {
            return null;
        }

        //未过期，直接返回店铺信息
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        Shop oldShop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        if(expireTime.isAfter(LocalDateTime.now())){
            return oldShop;
        }

        //已过期，开始缓存重建
        //1、获取互斥锁
        boolean obtainLockFlag = tryLock(RedisConstants.RedisShopConstants.LOCK_SHOP_KEY_PREFIX + id);

        //2、获取互斥锁失败：返回过期店铺信息
        if (!obtainLockFlag) {
            return oldShop;
        }

        //3、获取锁成功：Double Check
        String shopJsonStr = stringRedisTemplate.opsForValue().get(RedisConstants.RedisShopConstants.CACHE_SHOP_KEY_PREFIX + id);
        if (StrUtil.isNotBlank(shopJsonStr)) {
            RedisData redisDataObject = JSONUtil.toBean(shopJsonStr, RedisData.class);
            if(redisDataObject.getExpireTime().isAfter(LocalDateTime.now())){
                return JSONUtil.toBean((JSONObject) redisDataObject.getData(), Shop.class);
            }
        }

        //4、获取互斥锁成功：开启独立线程实现缓存重建
        CACHE_REBUILD_EXECUTOR.submit(() -> {
            try {
                saveShop2Redis(id, 20L);
            } finally {
                //释放锁
                unlock(RedisConstants.RedisShopConstants.LOCK_SHOP_KEY_PREFIX + id);
            }

        });
        return oldShop;
    }

    public void saveShop2Redis(Long id,long expire){
        //查询店铺数据
        Shop shop = getById(id);

        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //封装成逻辑过期
        RedisData redisData = new RedisData();
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expire));
        redisData.setData(shop);

        //写入redis
        stringRedisTemplate.opsForValue().set(RedisConstants.RedisShopConstants.CACHE_SHOP_KEY_PREFIX+id, JSONUtil.toJsonStr(redisData));
    }

    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key,
                "1",
                RedisConstants.RedisShopConstants.LOCK_SHOP_TTL,
                TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }

    /**
     * 根据id查询商铺信息-互斥锁解决缓存击穿问题
     * @param id
     * @return
     */
    private Shop queryWithMutex(Long id){
        //从redis查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(RedisConstants.RedisShopConstants.CACHE_SHOP_KEY_PREFIX + id);

        //存在直接返回
        if (shopJson != null) {
            if (StrUtil.isNotBlank(shopJson)) {
                Shop shop = JSONUtil.toBean(shopJson, Shop.class);
                return shop;
            }else {
                //店铺在数据库不存在，缓存了 ""
                return null;
            }
        }

        //缓存重建
        //1、获取互斥锁
        boolean obtainLockFlag = tryLock(RedisConstants.RedisShopConstants.LOCK_SHOP_KEY_PREFIX + id);
        Shop shop = null;

        try {
            //2、失败，休眠并重试
            if (!obtainLockFlag) {
                Thread.sleep(50);
                return queryWithMutex(id);
            }

            //3、成功：Double Check再次判断缓存是否存在
            if (shopJson != null) {
                if (StrUtil.isNotBlank(shopJson)) {
                    return JSONUtil.toBean(shopJson, Shop.class);
                }else {
                    //店铺在数据库不存在，缓存了 ""
                    return null;
                }
            }

            //4、成功，查询数据库，写入缓存
            //根据id查询数据库
            shop = getById(id);

            Thread.sleep(200);//模拟重建延迟

            //不存在，返回错误
            if (shop == null) {
                stringRedisTemplate.opsForValue().set(RedisConstants.RedisShopConstants.CACHE_SHOP_KEY_PREFIX + id, "",
                        RedisConstants.RedisCommonConstants.CACHE_NULL_TTL,
                        TimeUnit.MINUTES);

                return null;
            }

            //把数据写入redis
            stringRedisTemplate.opsForValue().set(RedisConstants.RedisShopConstants.CACHE_SHOP_KEY_PREFIX + id, JSONUtil.toJsonStr(shop),
                    RedisConstants.RedisShopConstants.CACHE_SHOP_TTL,
                    TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //4、释放互斥锁
            unlock(RedisConstants.RedisShopConstants.LOCK_SHOP_KEY_PREFIX + id);
        }
        return shop;
    }

    /**
     * 根据id查询商铺信息-NULL值解决缓存穿透问题
     * @param id
     * @return
     */
    private Shop queryWithPassThrough(Long id){
        //从redis查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(RedisConstants.RedisShopConstants.CACHE_SHOP_KEY_PREFIX + id);

        //存在直接返回
        if (shopJson != null) {
            if (StrUtil.isNotBlank(shopJson)) {
                Shop shop = JSONUtil.toBean(shopJson, Shop.class);
                return shop;
            }else {
                //店铺在数据库不存在，缓存了 ""
                return null;
            }
        }

        //根据id查询数据库
        Shop shop = getById(id);

        //不存在，返回错误
        if (shop == null) {
            stringRedisTemplate.opsForValue().set(RedisConstants.RedisShopConstants.CACHE_SHOP_KEY_PREFIX + id, "",
                    RedisConstants.RedisCommonConstants.CACHE_NULL_TTL,
                    TimeUnit.MINUTES);

            return null;
        }

        //把数据写入redis
        stringRedisTemplate.opsForValue().set(RedisConstants.RedisShopConstants.CACHE_SHOP_KEY_PREFIX + id, JSONUtil.toJsonStr(shop),
                RedisConstants.RedisShopConstants.CACHE_SHOP_TTL,
                TimeUnit.MINUTES);

        return shop;
    }

    /**
     * 根据id查询商铺信息-加redis缓存
     * @param id
     * @return
     */
    public Shop queryWithRedisCache(Long id) {
        //从redis查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(RedisConstants.RedisShopConstants.CACHE_SHOP_KEY_PREFIX + id);

        //存在直接返回
        if (StrUtil.isNotBlank(shopJson)) {
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }

        //根据id查询数据库
        Shop shop = getById(id);

        //不存在，返回错误
        if (shop == null) {
            return null;
        }

        //把数据写入redis
        stringRedisTemplate.opsForValue().set(RedisConstants.RedisShopConstants.CACHE_SHOP_KEY_PREFIX + id, JSONUtil.toJsonStr(shop),
                RedisConstants.RedisShopConstants.CACHE_SHOP_TTL,
                TimeUnit.MINUTES);

        return shop;
    }

    @Override
    @Transactional
    public Result update(Shop shop) {
        if (shop.getId() == null) {
            return Result.fail("店铺id不能为空！");
        }

        // 更新数据库
        updateById(shop);

        // 删除缓存
        stringRedisTemplate.delete(RedisConstants.RedisShopConstants.CACHE_SHOP_KEY_PREFIX + shop.getId());
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        //1、没传x、y，直接查询数据库
        if(x == null || y == null){
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }
        //3、传x、y，从redis查询
        //3.1、计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;

        //3.1、查询redis，按照距离排序，分页，结果：shopId、distance
        //geosearch g1 fromlonlat 116.397904 39.909005 byradius 10 km withdist
        GeoResults<RedisGeoCommands.GeoLocation<String>> geoResults = stringRedisTemplate.opsForGeo().search(
                RedisConstants.RedisShopConstants.SHOP_GEO_PREFIX + typeId.toString(),
                GeoReference.fromCoordinate(x, y),
                new Distance(5000),
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs()
                        .includeDistance()
                        .limit(end) //比如分页：第一页：1~10,第二页：11~20，但这里只能查询从第一个开始指定数量的数据，所以只能查询出来再逻辑分页
        );
        if(geoResults == null){
            return Result.ok(Collections.emptyList());
        }

        //3.2、从结果解析出shopId、距离
        List<Long> shopIdList = new ArrayList<>();
        Map<Long,Distance> distanceMap = new HashMap<>();
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> geoResultList = geoResults.getContent();
        if (geoResultList.size() <= from) {
            return Result.ok(Collections.emptyList());
        }
        geoResultList.stream()
                .skip(from)
                .forEach(geoResult -> {
                    //店铺id
                    String shopIdStr = geoResult.getContent().getName();
                    shopIdList.add(Long.valueOf(shopIdStr));
                    //距离
                    Distance distance = geoResult.getDistance();
                    distanceMap.put(Long.valueOf(shopIdStr),distance);
                });

        //3.3、从结果解析出shopId，根据shopId查询shop
        String shopIdStr = StrUtil.join(",", shopIdList);
        List<Shop> shopList = query()
                .in("id", shopIdList)
                .last("order by FIELD(id," + shopIdStr + ")")
                .list();
        shopList.forEach(shop -> {
            Distance distance = distanceMap.get(shop.getId());
            shop.setDistance(distance.getValue());
        });
        return Result.ok(shopList);

    }
}
